# -*- coding: utf-8 -*-
import sys
import os
import time
import win32gui
import win32con
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
from PyQt5.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        
        self.setWindowTitle("外部程序启动器")
        self.setGeometry(100, 100, 300, 200)
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        
        self.button = QPushButton("启动外部程序", self)
        self.button.setGeometry(100, 80, 100, 40)
        self.button.clicked.connect(self.start_external_program)
        
        self.process_id = None

    def find_and_minimize_window(self, window_title):
        """查找并最小化指定标题的窗口"""
        def callback(hwnd, extra):
            if win32gui.IsWindowVisible(hwnd):
                title = win32gui.GetWindowText(hwnd)
                if window_title in title:
                    win32gui.ShowWindow(hwnd, win32con.SW_MINIMIZE)
                    return False  # 找到后停止枚举
            return True
        
        win32gui.EnumWindows(callback, None)

    def start_external_program(self):
        if self.process_id is None:
            try:
                script_dir = os.path.dirname(os.path.abspath(__file__))
                exe_path = os.path.join(script_dir, "SMA_stp05.exe")
                
                if not os.path.exists(exe_path):
                    QMessageBox.critical(self, "错误", f"未找到程序: {exe_path}")
                    return
                
                os.chdir(script_dir)
                self.process_id = os.system(f'start "" "{exe_path}"')
                self.button.setText("停止程序")
                
                # 等待1秒后最小化外部程序窗口
                time.sleep(1)
                self.find_and_minimize_window("SMA_stp05")
                
            except Exception as e:
                QMessageBox.critical(self, "错误", f"启动失败: {str(e)}")
        else:
            os.system(f'taskkill /f /im SMA_stp05.exe')
            self.process_id = None
            self.button.setText("启动外部程序")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
